package com.cory.admin.sys.controller.admin;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cory.admin.sys.controller.AdminController;
import com.cory.admin.sys.domain.entity.SysResource;
import com.cory.admin.sys.service.SysResourceService;
import com.cory.boot.domain.bean.Result;
import com.cory.boot.domain.enumdef.EState;

/**
 * @author xiongcong
 * @date 2022-05-05
 */
@Controller
@RequestMapping("admin/sys/resource")
public class SysResourceController extends AdminController {
    @Autowired
    private SysResourceService sysResourceService;
    
    @RequestMapping("list")
    public String list(SysResource param, Model model) {
        param.setUserType(super.getPrincipal().getUserType());
        model.addAttribute("list", sysResourceService.sortList(param));
        return "admin/sys/resource/list";
    }
    
    @RequestMapping("form")
    public String form(SysResource info, Model model) {
        Integer pid = info.getPid();
        if (info.getId() != null) {
            info = sysResourceService.getById(info.getId());
            pid = info.getPid();
        } 
        if (pid != null && pid != 0) {
            model.addAttribute("parentInfo", sysResourceService.getById(pid));
        }
        model.addAttribute("info", info);
        return "admin/sys/resource/form";
    }
    
    @RequestMapping("save")
    @ResponseBody
    public Result<?> save(SysResource info) {
        
        if (StringUtils.isNotBlank(info.getPermission())) {
            QueryWrapper<SysResource> wrapper = new QueryWrapper<>();
            wrapper.ne("state", EState.DELETE.key).eq("permission", info.getPermission()).eq("user_type", super.getPrincipal().getUserType());
            
            SysResource tmp = sysResourceService.getOne(wrapper);
            if (tmp != null && (info.getId() == null || !info.getId().equals(tmp.getId()))) {
                return Result.fail("权限标志已存在");
            }
        }
        
        if (info.getId() == null) {
            info.setUserType(super.getPrincipal().getUserType());
            sysResourceService.save(info);
        } else {
            sysResourceService.updateById(info);
        }
        
        return Result.success("保存成功");
    }
    
    @RequestMapping("delete")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<?> delete(Integer id) {
        sysResourceService.delete(id);
        return Result.success("删除成功");
    }
}
